package machineinfo

import (
	"fmt"
	"os"
	"sync"

	"github.com/google/cadvisor/fs"
	"github.com/google/cadvisor/machine"
	"github.com/google/cadvisor/utils/sysfs"
)

var initOnce sync.Once

func InitializeMachineInfo() error {
	var retErr error

	initOnce.Do(func() {
		fsContext := fs.Context{}
		sysFs := sysfs.NewRealSysFs()

		fsInfo, err := fs.NewFsInfo(fsContext)
		if err != nil {
			retErr = fmt.Errorf("failed to initiate FsInfo, err: %v", err)
			return
		}

		inHostNamespace := false
		if _, err = os.Stat("/rootfs/proc"); os.IsNotExist(err) {
			inHostNamespace = true
		}

		machineInfo, err := machine.Info(sysFs, fsInfo, inHostNamespace)
		if err != nil {
			retErr = fmt.Errorf("failed to initiate machine info, err: %v", err)
			return
		}
		gMachineInfo = machineInfo
	})

	return retErr
}
